package com.hnichr.ump.plan.service.impl;

import com.hnichr.ump.common.plan.entity.PlanGroup;
import com.hnichr.ump.common.plan.entity.PlanGroupUser;
import com.hnichr.ump.common.plan.service.PlanAuthService;
import com.hnichr.ump.common.plan.vo.PlanAuthVo;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.security.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.hnichr.ump.common.plan.Constants;

import java.util.List;

@Service
@Slf4j
public class PlanAuthServiceImpl implements PlanAuthService {


    @Override
    @Transactional(readOnly = true)
    public PlanAuthVo getUserAuth(String username){
        if(StringUtils.isBlank(username)){
            log.error(">>>>>>>>>>>>>>username为空");
            throw new RuntimeException("username为空");
        }
        List<PlanGroupUser> groupUserList = JpaUtil.linq(PlanGroupUser.class).equal("username",username).list();
        if(CollectionUtils.isEmpty(groupUserList)){
            return PlanAuthVo.getNoAuth();
        }
        if(groupUserList.size()>1){
            log.error(">>>>>>>>>>>>>>用户{}拥有至少两种角色",username);
            throw new RuntimeException("用户拥有至少两种角色");
        }
        PlanGroupUser groupUser = groupUserList.get(0);
        PlanGroup planGroup = JpaUtil.getOne(PlanGroup.class,groupUser.getGroupId());
        PlanAuthVo planAuthVo;
        switch (planGroup.getGroupCode()){
            case Constants.COMPANY_LEADER:
                planAuthVo = PlanAuthVo.getCompanyLeader();
                break;
            case Constants.PLAN_ADMIN:
                planAuthVo = PlanAuthVo.getPlanAdmin();
                break;
            case Constants.DEPT_LEADER:
                planAuthVo = PlanAuthVo.getDeptLeader();
                break;
            case Constants.STAFF:
                planAuthVo = PlanAuthVo.getStaff();
                break;
            default:
                planAuthVo = PlanAuthVo.getNoAuth();
        }
        return planAuthVo;
    }

    @Override
    @Transactional(readOnly = true)
    public PlanAuthVo getUserAuth(){
        String username = SecurityUtils.getLoginUsername();
        return getUserAuth(username);
    }
}
